﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.entity.Device;
using tcm.request;
using tcm.response;
using tcm.utils;

namespace tcm.Controller
{
    [ApiController]
    [Route("tcm/order")]
    public class OrderController : GCCAPIControllerBase
    {
        public OrderController(AbsGCCContext context) : base(context)
        {
        }

        
        [HttpGet("dispensing")]
        public DataResponse<List<Dispensing>> dispensing([FromQuery] OrderQueryReq req)
        {
            var dbquery = GCCEntrance.DBManager.GlobalDB.Select<Order, User, Cabinet, User, Device, Site >()
                .InnerJoin((a, b, c, d, e, f) => a.user_id == b.id)
                .LeftJoin((a, b, c, d, e, f) => a.cabinet_id == c.id)
                .LeftJoin((a, b, c, d, e, f) => a.delivery_id == d.id)
                .LeftJoin((a, b, c, d, e, f) => c.device_id == e.id)
                .LeftJoin((a, b, c, d, e, f) => a.site_id == f.id)
             //   .Where((a, b, c, d, e, f) => new[] {1, 2, 5 }.Contains(a.status))
                .WhereIf(req.order_id != null, (a, b, c, d, e, f) => a.id == req.order_id)
                .WhereIf(!string.IsNullOrEmpty(req.wxId), (a, b, c, d, e, f) => b.wx_id == req.wxId)
                .WhereIf(req.userId != null, (a, b, c, d, e, f) => b.id == req.userId)
                .WhereIf(!string.IsNullOrEmpty(req.userName), (a, b, c, d, e, f) => b.uname == req.userName)
                .WhereIf(req.beginTime != null, (a, b, c, d, e, f) => a.create_date >= req.beginTime)
                .WhereIf(req.endTime != null, (a, b, c, d, e, f) => a.create_date <= req.endTime)
                .WhereIf(req.status != null, (a, b, c, d, e, f) => a.status == req.status)
                .WhereIf((req.is_dispensing == null || req.is_dispensing == 0) && req.status == null, (a, b, c, d, e, f) => a.status == 1) //默认只查询代发药状态
                .WhereIf(req.is_dispensing == 1, (a, b, c, d, e, f) => a.status > 1) 
                .WhereIf(req.is_apply != null, (a, b, c, d, e, f) => a.is_apply == req.is_apply)
                .WhereIf(req.type != null, (a, b, c, d, e, f) => a.type == req.type)
                .OrderBy((a, b, c, d, e, f) => a.create_date)
                .Count(out var count)
                .Page(req.PageIndex ?? 1, req.PageSize)
                .ToList((a, b, c, d, e, f) => new { a, b, c, d, e, f, phm_list_id = GCCEntrance.DBManager.GlobalDB.Select<UesrPhmList>().Where(b => b.order_id == a.id).First(b => b.phm_list_id),
                    list_name = GCCEntrance.DBManager.GlobalDB.Select<UesrPhmList, PhmList>().InnerJoin((b, c) => b.phm_list_id == c.id).Where((b, c) => b.order_id == a.id).First((b, c) => c.list_name),
                });

            List<Dispensing> orderList = new List<Dispensing>();
            if (dbquery != null)
            {
                for (int i = 0; i < dbquery.Count; i++)
                {
                    Dispensing dis = BeanUtils.copy<Dispensing, Order>(dbquery[i].a);
                    dis.user = dbquery[i].b;
                    dis.cabinet = dbquery[i].c;
                    dis.delivery = dbquery[i].d;
                    dis.site = dbquery[i].f;
                    dis.phm_list_id = dbquery[i].phm_list_id;
                    dis.list_name = dbquery[i].list_name;
                    orderList.Add(dis);
                }
            }

            return HandleData(orderList, count);
        }

        [HttpPost("dispensing")]
        public Result updateDispensing(DispensingReq req)
        { 
            Result result = new Result();
            result.id = req.order_id;
            result.code = GlobalConstant.Success;
            result.msg = "发药完成!";

            if (req.order_id == null || req.order_id == 0) 
            {
                result.code = GlobalConstant.Success;
                result.msg = "order_id为空!";
                return result;
            }

            if (req.cabinet_id == null || req.cabinet_id == 0)
            {
                result.code = GlobalConstant.Success;
                result.msg = "cabinet_id为空!";
                return result;
            }

            List<Cabinet> cabinetList = GCCEntrance.DBManager.GlobalDB.Select<Cabinet>().Where(a => a.id == req.cabinet_id).ToList();
            if (cabinetList == null || cabinetList.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "根据订单cabinet_id无法查询出来药柜信息!";
                return result;
            }
            

            List<Order> list = GCCEntrance.DBManager.GlobalDB.Select<Order>().Where(a => a.id == req.order_id).ToList();
            if (list == null || list.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "根据订单id无法查询出来订单数据!";
                return result;
            }


            Order order = list.First();
            if (order.status != 1) 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "订单不是待发药状态!";
                return result;
            }


            Cabinet cabinet = cabinetList.First();
            if (cabinet.is_have == 1)
            {
                // 有药，直接到客户待取药，不需要预约
                order.status = 5;
                // order.is_apply = 0;
                result.msg = "发药完成，药柜有药！";
            }
            else 
            {
                if (req.delivery_id != null)
                {
                    List<User> deliveryList = GCCEntrance.DBManager.GlobalDB.Select<User>().Where(a => a.id == req.delivery_id).ToList();
                    if (deliveryList == null || deliveryList.Count == 0)
                    {
                        result.code = GlobalConstant.Failure;
                        result.msg = "根据delivery_id无法查询出来快递员信息!";
                        return result;
                    }
                }

                // 配送员
                order.delivery_id = req.delivery_id;

                // 更新订单状态为待配送
                order.status = 2;
                //order.is_apply = 1;
                order.apply_valid = (DateTime)req.apply_valid;
            }

            order.cabinet_id = req.cabinet_id;
            order.update_date = DateTime.Now;

            // 更新
            int m = GCCEntrance.DBManager.GlobalDB.Update<Order>(req.order_id).SetSource(order).ExecuteAffrows();
            if (m == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "更新数据库失败！";
                return result;
            }
            else
            {
                // 发药完成，药柜更新成占用状态
                cabinet.is_use = 1;
                cabinet.update_date = DateTime.Now;
                _=GCCEntrance.DBManager.GlobalDB.Update<Cabinet>(cabinet.id).SetSource(cabinet).ExecuteAffrows();
            }

            // 微信通知
            if (req.toSendNotice == 1)
            {
                if (cabinet.is_have == 1)
                {
                    // 通知客户
                    var msg = WeChatSendMessage.Instance.OrderSupplyNotice(order.id);
                }
                else {
                    // 通知配送员
                    var msg = WeChatSendMessage.Instance.SupplyOrderNotice(order.id);
                }
                    
            }

            return result;
        }

        [HttpGet("query")]
        public DataResponse<List<OrderInfo>> query([FromQuery] OrderQueryReq req)
        {
            var dbquery = GCCEntrance.DBManager.GlobalDB.Select<Order, User, UserReport, Site>()
                .InnerJoin((a, b, c, d) => a.user_id == b.id).InnerJoin((a, b, c, d) => a.id == c.order_id)
                .LeftJoin((a, b, c, d) => a.site_id == d.id)
                .WhereIf(!string.IsNullOrEmpty(req.wxId), (a, b, c, d) => b.wx_id == req.wxId)
                .WhereIf(req.userId != null, (a, b, c, d) => b.id == req.userId)
                .WhereIf(!string.IsNullOrEmpty(req.userName), (a, b, c, d) => b.uname == req.userName)
                .WhereIf(req.beginTime != null, (a, b, c, d) => a.create_date >= req.beginTime)
                .WhereIf(req.endTime != null, (a, b, c, d) => a.create_date <= req.endTime)
                .WhereIf(req.status != null, (a, b, c, d) => a.status == req.status)
                .WhereIf(req.is_apply != null, (a, b, c, d) => a.is_apply == req.is_apply)
                .WhereIf(req.type != null, (a, b, c, d) => a.type == req.type)
                .WhereIf(req.type == null, (a, b, c, d) => a.type == 0)
                .OrderByDescending((a, b, c, d) => a.create_date)
                .Count(out var count)
                .Page(req.PageIndex ?? 1, req.PageSize)
                .ToList((a, b, c, d) => new { a, b, c, d });

            List<OrderInfo> orderList = new List<OrderInfo>();
            if (dbquery != null)
            {
                for (int i = 0; i < dbquery.Count; i++)
                {
                    OrderInfo orderInfo = BeanUtils.copy<OrderInfo, Order>(dbquery[i].a);
                    orderInfo.report_id = dbquery[i].c.id;
                    orderInfo.name = dbquery[i].c.name;
                    orderInfo.user = dbquery[i].b;
                    orderInfo.site = dbquery[i].d;
                    orderList.Add(orderInfo);
                }
            }

            return HandleData(orderList, count);
        }

        [HttpPut("update")]
        public Result update(OrderReq req)
        {  
            Result result = new Result();
            result.code = GlobalConstant.Success;

            if (req.order_id == 0 || req.order_id == null)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "订单id为空!";
                return result;
            }

            List<Order> orderList = GCCEntrance.DBManager.GlobalDB.Select<Order>().Where(a => a.id == req.order_id).ToList();
            if (orderList == null || orderList.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "订单id无法查询到订单信息!";
                return result;
            }

            Order order = orderList[0];
            BeanUtils.copy<Order, OrderReq>(req, ref order);

            // 更新
            int m = GCCEntrance.DBManager.GlobalDB.Update<Order>()
                .SetIf(req.cabinet_id != null && req.cabinet_id!=0, a => a.cabinet_id == req.cabinet_id)
                .SetIf(req.is_apply != null, a => a.is_apply == req.is_apply)
                .SetIf(req.status != null, a => a.status == req.status).Where(a => a.id == req.order_id).ExecuteAffrows();

            if (m <= 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "更新失败！";
            }
            else
            {
                result.id = req.order_id;
            }

            return result;
        }


        [HttpGet("queryOrder")]
        public DataResponse<List<OrderInfo>> queryOrder([FromQuery] OrderQueryReq req)
        {
            var dbquery = GCCEntrance.DBManager.GlobalDB.Select<Order, User, UserReport>()
                .InnerJoin((a, b, c) => a.user_id == b.id).InnerJoin((a, b, c) => a.id == c.order_id)
                .WhereIf(!string.IsNullOrEmpty(req.wxId), (a, b, c) => b.wx_id == req.wxId)
                .WhereIf(req.userId != null, (a, b, c) => b.id == req.userId)
                .WhereIf(!string.IsNullOrEmpty(req.userName), (a, b, c) => b.uname == req.userName)
                .WhereIf(req.beginTime != null, (a, b, c) => a.create_date >= req.beginTime)
                .WhereIf(req.endTime != null, (a, b, c) => a.create_date <= req.endTime)
                .WhereIf(req.status != null, (a, b, c) => a.status == req.status)
                .WhereIf(req.is_apply != null, (a, b, c) => a.is_apply == req.is_apply)
                .WhereIf(req.type != null, (a, b, c) => a.type == req.type)
                .WhereIf(req.type == null, (a, b, c) => a.type == 0)
                .Where((a, b, c) => new[] { 1, 2 }.Contains(a.is_apply))
                .Count(out var count)
                .Page(req.PageIndex ?? 1, req.PageSize)
                .ToList((a, b, c) => new { a, b, c });

            List<OrderInfo> orderList = new List<OrderInfo>();
            if (dbquery != null)
            {
                for (int i = 0; i < dbquery.Count; i++)
                {
                    OrderInfo orderInfo = BeanUtils.copy<OrderInfo, Order>(dbquery[i].a);
                    orderInfo.report_id = dbquery[i].c.id;
                    orderInfo.name = dbquery[i].c.name;
                    orderInfo.user = dbquery[i].b;
                    orderList.Add(orderInfo);
                }
            }

            return HandleData(orderList, count);
        }

        [HttpGet("queryDetail")]
        public OrderDetailRes queryDetail(long orderId)
        {
            OrderDetailRes result = new OrderDetailRes();
            result.code = GlobalConstant.Success;
            result.id = orderId;
            var dbquery = GCCEntrance.DBManager.GlobalDB.Select<Order, User>()
                .InnerJoin((a, b) => a.user_id == b.id)
                .Where((a, b) => a.id == orderId)
                .ToList((a, b) => new { a, b });
            if (dbquery == null || dbquery.Count == 0)
            {
                result.msg = "orderId:" + orderId + "没有数据！";
                result.code = GlobalConstant.Failure;
                return result;
            }
            result.order = dbquery[0].a;
            result.user = dbquery[0].b;

            // 获取药品信息
            var phmListQuery = GCCEntrance.DBManager.GlobalDB.Select<Pharmaceutical, UesrPhmList>()
                .InnerJoin((a, b) => a.id == b.phm_id)
                .Where((a, b) => b.order_id == orderId)
                .ToList((a, b) => new { a, b });

            if (phmListQuery != null && phmListQuery.Count > 0)
            {
                List<UserPhm> phmList = new List<UserPhm>();
                for (int i = 0; i < phmListQuery.Count; i++)
                {
                    UserPhm userPhm = BeanUtils.copy<UserPhm, Pharmaceutical>(phmListQuery[i].a);
                    userPhm.num = phmListQuery[i].b.num;
                    phmList.Add(userPhm);
                }

                result.phmList = phmList;

                List<PhmList> phmLists = GCCEntrance.DBManager.GlobalDB.Select<PhmList>().Where(a => a.id == phmListQuery[0].b.phm_list_id).ToList();
                if (phmLists != null && phmLists.Count > 0)
                {
                    result.phmListInfo = phmLists[0];
                }
            }


            return result;
        }

        [HttpPost("orderTime")]
        public Result orderTime(OrderTimeReq req)
        {
            Result result = new Result();
            result.id = req.id;
            result.code = GlobalConstant.Success;
            result.msg = "预约成功!";

            if (req.id == null || req.id == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "预约id为空!";
                return result;
            }

            if (req.beginTime == null)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "预约开始时间为空!";
                return result;
            }

            if (req.endTime == null)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "预约结束时间为空!";
                return result;
            }

            if (req.beginTime >= req.endTime)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "预约开始时间" + req.beginTime + "必须在预约结束时间" + req.endTime + "之前!";
                return result;
            }

            List<Order> list = GCCEntrance.DBManager.GlobalDB.Select<Order>().Where(a => a.id == req.id).ToList();
            if (list == null || list.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "根据预约id无法查询出来预约数据!";
                return result;
            }
            Order order = list[0];

            if (order.is_apply != 1) 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "不是待预约的状态!";
                return result;
            }

            if (order.apply_valid >= req.beginTime)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "预约时间必须在申请有效开始时间之后!";
                return result;
            }

            if (order.apply_valid >= req.endTime)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "预约时间必须在申请有效开始时间之后!";
                return result;
            }

            order.start_date = req.beginTime;
            order.end_date = req.endTime;
            order.update_date = DateTime.Now;
            order.is_apply = 2;

            // 更新
            int m = GCCEntrance.DBManager.GlobalDB.Update<Order>(req.id).SetSource(order).ExecuteAffrows();
            if (m == 0)
            {
                result.msg = "更新失败！";
                result.code = GlobalConstant.Failure;
                return result;
            }

            return result;
        }

        //delivery
        [HttpGet("delivery/query")]
        public DataResponse<List<entity.Delivery>> queryDelivery(string wxId)
        {
            List<entity.Delivery> list = GCCEntrance.DBManager.GlobalDB.Select<entity.Delivery>()
                 .WithSql("select o.*, u.uname delivery," +
                         "  (select max(uname) from tcm_user where id = o.user_id) user_name," +
                         "  (select max(user_name) from tcm_sys_user u, tcm_user_report r where u.id = r.doctor_id and r.order_id = o.id) doctor_name," +
                         "  (select max(cabinet_no) from tcm_cabinet d where d.id = o.cabinet_id) cabinet_no" +
                         "  from tcm_order o, tcm_user u" +
                         " where o.delivery_id = u.id" +
                         "   and o.`status` = 2 and u.wx_id = ?wxId", new { wxId = wxId }).ToList();
            return HandleData(list);
        }

        [HttpGet("delivery/queryDetail")]
        public DataResponse<List<UserPhm>> queryDeliveryDetail(long orderId)
        {
            List<UserPhm> list = GCCEntrance.DBManager.GlobalDB.Select<UserPhm>()
                 .WithSql("select l.*, u.num " +
                          "  from tcm_uesr_phm_list u, tcm_pharmaceutical l" +
                          " where u.phm_id = l.id" +
                          "   and u.order_id = ?orderId", new { orderId = orderId }).ToList();
            return HandleData(list);
        }


        [HttpPost("delivery")]
        public Result delivery(long orderId)
        {
            Result result = new Result();
            result.id = orderId;
            result.code = GlobalConstant.Success;
            result.msg = "完成立即配送!";

            List<Order> list = GCCEntrance.DBManager.GlobalDB.Select<Order>().Where(a => a.id == orderId).ToList();
            if (list == null || list.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "根据订单id无法查询出来配送数据!";
                return result;
            }
            Order order = list[0];

            if (order.status != 2) { 
                result.code = GlobalConstant.Failure;
                result.msg = "订单信息不在待配送状态！";
                return result;
            }

            order.update_date = DateTime.Now;
            order.status = 3;

            // 更新
            int m = GCCEntrance.DBManager.GlobalDB.Update<Order>(orderId).SetSource(order).ExecuteAffrows();
            if (m == 0)
            {
                result.code = GlobalConstant.Failure;
                return result;
            }

            // 药柜表数量增加1
            return result;
        }

        [HttpGet("queryPay")]
        public DataResponse<List<QueryPayReq>> queryPay([FromQuery] PayReq req)
        {
            var list = GCCEntrance.DBManager.GlobalDB.Select<Order, User, Cabinet, Device, Site>()
                .InnerJoin((a, b, c, d, e) => a.user_id == b.id)
                .LeftJoin((a, b, c, d, e) => a.cabinet_id == c.id)
                .LeftJoin((a, b, c, d, e) => c.device_id == d.id)
                .LeftJoin((a, b, c, d, e) => d.site_id == e.id)
                .Where((a, b, c, d, e) => a.type == 0)
                .WhereIf(!string.IsNullOrEmpty(req.siteName), (a, b, c, d, e) => e.site_name == req.siteName)
                .WhereIf(req.beginTime != null, (a, b, c, d, e) => a.pay_date >= req.beginTime)
                .WhereIf(req.endTime != null, (a, b, c, d, e) => a.pay_date <= req.endTime)
                .WhereIf(req.payStatus != null, (a, b, c, d, e) => a.pay_status == req.payStatus)
                .OrderByDescending((a, b, c, d, e) => a.create_date)
                .Count(out var count)
                .Page(req.PageIndex ?? 1, req.PageSize).ToList((a, b, c, d, e) => new { a, b, c, d, e,
                    list_name = GCCEntrance.DBManager.GlobalDB.Select<UesrPhmList, PhmList>().InnerJoin((b, c) => b.phm_list_id == c.id).Where((b, c) => b.order_id == a.id).First((b, c) => c.list_name),
                    siteName = GCCEntrance.DBManager.GlobalDB.Select<Site>().Where(b => b.id == d.site_id).First(b => b.site_name)
                });

            List<QueryPayReq> reqList = new List<QueryPayReq>();
            for (int i = 0; i < list.Count; i++) 
            {
                QueryPayReq pay = new QueryPayReq();
                pay.orderId = list[i].a.id;
                pay.uname = list[i].b.uname;
                pay.payStatus = list[i].a.pay_status;
                pay.price = list[i].a.price;
                pay.payType = list[i].a.pay_type;
                pay.phmListName = list[i].list_name;
                pay.siteName = list[i].siteName;

                if (list[i].a.pay_date != null && list[i].a.pay_date > DateTime.MinValue) 
                {
                    pay.payTime = list[i].a.pay_date.ToString("yyyy-MM-dd HH:mm:ss");
                }

                reqList.Add(pay);
            }

            return HandleData(reqList, count);
        }

        [HttpGet("statistics")]
        public StatisticsRes statistics()
        {
            StatisticsRes res = new StatisticsRes();
            res.code = GlobalConstant.Success;
            
            DateTime lastYear = new DateTime(DateTime.Now.AddYears(-1).Year, 1, 1, 0, 0, 0);
            DateTime nextYear = new DateTime(DateTime.Now.AddYears(1).Year, 1, 1, 0, 0, 0);

            res.msg = lastYear.ToString() + "~" + nextYear.ToString();
            var sql = new StringBuilder();
            _ = sql.Append("select date_format(create_date, '%Y-%m') month, sum(price) sum " +
                        "from tcm_order where pay_status = 1 and type = 0  ");
            _ = sql.Append(string.Format(" and pay_date >= '{0}' ", lastYear.ToString("yyyy-MM-dd HH:mm:ss")));
            _ = sql.Append(string.Format(" and pay_date <'{0}' ", nextYear.ToString("yyyy-MM-dd HH:mm:ss")));
            _ = sql.Append("GROUP BY date_format(create_date, '%Y-%m') ");

            List<StatisticsMonth> list = GCCEntrance.DBManager.GlobalDB.Select<StatisticsMonth>().WithSql(sql.ToString()).ToList();

            // 各个季度的输入汇总
            var quarterSql = new StringBuilder();
            _ = quarterSql.Append("select CONCAT(date_format(create_date, '%Y'),QUARTER(create_date)) `quarter`, sum(price) sum " +
                        "from tcm_order where pay_status = 1  and type = 0  ");
            _ = quarterSql.Append(string.Format(" and pay_date >= '{0}' ", lastYear.ToString("yyyy-MM-dd HH:mm:ss")));
            _ = quarterSql.Append(string.Format(" and pay_date <'{0}' ", nextYear.ToString("yyyy-MM-dd HH:mm:ss")));
            _ = quarterSql.Append("GROUP BY `quarter`");
            
            List<StatisticsQuarter> quarterList = GCCEntrance.DBManager.GlobalDB.Select<StatisticsQuarter>().WithSql(quarterSql.ToString()).ToList();

            
            var typeSql = new StringBuilder();
            _ = typeSql.Append("select pay_type, sum(price) sum " +
                        "from tcm_order where pay_status = 1  and type = 0  ");
            //_ = typeSql.Append(string.Format(" and create_date >= '{0}' ", lastYear));
            //_ = typeSql.Append(string.Format(" and create_date <'{0}' ", nextYear));
            _ = typeSql.Append("GROUP BY pay_type");

            // 支付类型汇总
            List<StatisticsType> typeList = GCCEntrance.DBManager.GlobalDB.Select<StatisticsType>().WithSql(typeSql.ToString()).ToList();

            res.typeList = typeList;
            res.monthList = list;
            res.quarterList = quarterList;
            return res;
        }

        [HttpPost("deliverying")]
        public Result addDelivery(DeliveryReq req)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            // 检查药斗里面的药品是否和配送的药品一样

            List<Cabinet> cabinetList = GCCEntrance.DBManager.GlobalDB.Select<Cabinet>().Where(a => a.id == req.cabinet_id).ToList();
            if (cabinetList == null || cabinetList.Count == 0) 
            {
                result.code = GlobalConstant.Failure;
                result.msg = "所选药斗不存在！";
                return result;
            }

            long cabinetPhmListId = cabinetList[0].phm_list_id;
            if (cabinetPhmListId != 0 && cabinetPhmListId != null) 
            {
                // 药斗存在处方药
                if (cabinetPhmListId != req.phm_list_id) 
                {
                    if (cabinetList[0].num > 0)
                    {
                        result.code = GlobalConstant.Failure;
                        result.msg = "配送处方和所选药斗的处方不一致！";
                        return result;
                    }                   
                }
            }
            
            long orderId = IdUtils.getId();
            Order order = new Order();
            order.id = orderId;
            order.user_id = req.delivery_id;
            order.delivery_id = req.delivery_id;
            order.cabinet_id = req.cabinet_id;
            order.site_id = req.site_id;
            order.apply_valid = req.delivery_date;
            order.type = 1;
            order.status = 2;

            // 根据处方药id查询处方信息
            var phmList = GCCEntrance.DBManager.GlobalDB.Select<Pharmaceutical, PhmListRelation>()
               .InnerJoin((a, b) => a.id == b.phm_id).Where((a, b) => b.phm_list_id == req.phm_list_id).ToList((a, b) => new { a, b });
            if (phmList == null || phmList.Count == 0)
            {
                result.code = GlobalConstant.Failure;
                result.msg = "根据药方id无法查询药品信息！";
                return result;
            }

            // 药品总价
            Decimal price = 0;

            // 关联药方和订单信息
            List<UesrPhmList> uesrPhmLists = new List<UesrPhmList>();
            for (int i = 0; i < phmList.Count; i++)
            {
                int userPhmNum = phmList[i].b.phm_num * (int)req.num;
                UesrPhmList userPhmList = new UesrPhmList();
                userPhmList.id = IdUtils.getId(i);
                userPhmList.phm_id = phmList[i].a.id;
                userPhmList.phm_list_id = req.phm_list_id;
                userPhmList.num = userPhmNum;
                userPhmList.order_id = orderId;
                userPhmList.user_id = req.delivery_id;
                userPhmList.create_date = DateTime.Now;
                userPhmList.update_date = DateTime.Now;

                userPhmList.create_by = req.delivery_id;
                userPhmList.update_by = req.delivery_id;
                uesrPhmLists.Add(userPhmList);

                Decimal phmPrice = Convert.ToDecimal(phmList[i].a.price);
                price = Decimal.Add(price, Decimal.Multiply(userPhmNum, phmPrice));
            }
            _ = GCCEntrance.DBManager.GlobalDB.Insert<UesrPhmList>(uesrPhmLists).ExecuteAffrows();

            order.price = Decimal.ToDouble(price);
            _ = GCCEntrance.DBManager.GlobalDB.Insert<Order>(order).ExecuteAffrows();

            _ = GCCEntrance.DBManager.GlobalDB.Update<Cabinet>().Set(a => a.phm_list_id == req.phm_list_id).Where(a => a.id == req.cabinet_id).ExecuteAffrows();
            result.id = orderId;

            // 更新处方药品数量
            //if (req.num != null && req.num > 0) 
            //{
            //    _ = GCCEntrance.DBManager.GlobalDB.Update<PhmListRelation>().Set(a => a.phm_num == req.num).Where(a => a.phm_list_id == req.phm_list_id).ExecuteAffrows();
           // }
            
            // 微信通知
            if (req.toSendNotice == 1)
            {
                // 通知配送员
                var msg = WeChatSendMessage.Instance.SupplyOrderNotice(order.id);

            }
            return result;
        }
    }
}
